package com.mosai.smartmedical;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.kongqw.serialportlibrary.Device;
import com.kongqw.serialportlibrary.SerialPortFinder;
import com.kongqw.serialportlibrary.SerialPortManager;
import com.kongqw.serialportlibrary.listener.OnOpenSerialPortListener;
import com.kongqw.serialportlibrary.listener.OnSerialPortDataListener;

import java.io.File;
import java.util.ArrayList;

public class SerialActivity extends AppCompatActivity {
    public static final String TAG = SerialActivity.class.getSimpleName();
    SerialPortManager serialPortManager;
    TextView tvContent;
    EditText etContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate: ");
        setContentView(R.layout.activity_serial);

        tvContent = findViewById(R.id.tvContent);
        etContent = findViewById(R.id.etContent);

        serialPortManager = new SerialPortManager();
        serialPortManager.setOnOpenSerialPortListener(new OnOpenSerialPortListener() {
            @Override
            public void onSuccess(File file) {
                Log.i(TAG, "OpenSerialPort onSuccess: file: " + file);
            }

            @Override
            public void onFail(File file, Status status) {
                Log.i(TAG, "OpenSerialPort onFail: file: " + file + " status: " + status);
            }
        });
        serialPortManager.setOnSerialPortDataListener(new OnSerialPortDataListener() {
            @Override
            public void onDataReceived(byte[] bytes) {
                String s = bytesToHex(bytes);
                runOnUiThread(() -> {
                    tvContent.append("Received: " + s);
                    tvContent.append("\n");
                });
                Log.i(TAG, "OpenSerialPort onDataReceived: bytes: " + s);
            }

            @Override
            public void onDataSent(byte[] bytes) {
                String s = bytesToHex(bytes);

                runOnUiThread(() -> {
                    tvContent.append("Sent: " + s);
                    tvContent.append("\n");
                });
                Log.i(TAG, "OpenSerialPort onDataSent: bytes: " + s);
            }
        });


        SerialPortFinder serialPortFinder = new SerialPortFinder();
        ArrayList<Device> devices = serialPortFinder.getDevices();
        Log.i(TAG, "onCreate: devices: " + devices.size());
        for (Device device : devices) {
            Log.i(TAG, "onCreate: device: "
                    + " name: " + device.getName()
                    + " root: " + device.getRoot()
                    + " file: " + device.getFile()
            );
        }

        serialPortManager.openSerialPort(new File("/dev/ttyS0"), 9600);
//        serialPortManager.openSerialPort(devices.get(3).getFile(), 9600);
    }

    public void onSend(View view) {
        Editable text = etContent.getText();
        if (text == null || text.toString().isEmpty()) {
            return;
        }
        String s = text.toString();
        byte[] bytes = hexToByteArray(s);
        serialPortManager.sendBytes(bytes);
    }

    public static byte[] hexToByteArray(String inHex) {
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            //奇数
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        } else {
            //偶数
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = hexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    public static byte hexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    @Override
    protected void onDestroy() {
        serialPortManager.closeSerialPort();
        super.onDestroy();
    }
}
